﻿using ADODB;
using fuzhu;
using LH.Model.ST;
using SqlSuarEntity;
using SqlSugar;
using System.Data;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.XXXEntities;
using ZDEntity;

namespace Yonyou.U8.BO
{

    public class AdjustPVouchVM : ST_AdjustPVouch
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public bool bWMS = false;
        public string cDatabase = "";


        public AdjustPVouchVM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }



        public RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";

                foreach (Body body in bodies)
                {
                    body.editprop = "A";
                }

                string cRe = GetRdInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }

                //调拨单，额外增加其他出入库单的处理
                if (!AdjustPVouchDALCO.AddVerifyAdjustPVouch(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //审核失败后，检查是否有采购入库单生成，如果有，则删除
                    string cerr2 = "";
                    if (!string.IsNullOrEmpty(id))
                    {
                        AdjustPVouchDALCO.VerifyAdjustPVouch(id, xmlConfig, "delete", out cerr2);
                    }

                    return DBService.ReErrObject("新增失败：" + err);
                } 
                else
                {

                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        //不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                        if (!bWMS)
                        {

                            if (ccode != head.cVouchCode && head.cVouchCode != WMSPara.rdTVCode)
                            {
                                //单据编码选项判断
                                string sqlrep = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0313'");
                                int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sqlrep));
                                if (iRepeat == 1)
                                {
                                    string cerr2 = "";
                                    AdjustPVouchDALCO.VerifyAdjustPVouch(id, xmlConfig, "unverify,delete", out cerr2);
                                    return DBService.ReOKObject("单据已生成，重复");
                                }
                            }
                        }
                        else
                        {
                            //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                            string cParentid = head.cDefine10;
                            if (!string.IsNullOrEmpty(cParentid))
                            {
                                //检查cParentid 是否存在
                                string sqlcx = string.Format(@"select count(*) sl from AdjustPVouch a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                                int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                                if (icntUniq > 0)
                                {
                                    AdjustPVouchDALCO.VerifyAdjustPVouch(id, xmlConfig, "unverify,delete", out _);
                                    return DBService.ReOKObject("之前单据已生成，重复");
                                }
                            }

                        }
                         
                    }


                }
                //生成的id赋值
                head.Id = id;
                head.cVouchCode = ccode;
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }



        public string GetRdInfo()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        string cInvCode = bodies[i].cInvCode;


                        InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode, bodies[i].dMadeDate, bodies[i].dDisDate);
                        if (invProperty == null)
                        {
                            return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), cInvCode);
                        }
                        //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                        if (invProperty.iGroupType != "0")
                        {
                            //辅助计量单位来源于来源单据，如果没有取库存单位
                            if (string.IsNullOrEmpty(bodies[i].cAssUnit))
                            {
                                bodies[i].cAssUnit = invProperty.cSTComUnitCode;
                            }
                            //没有换算率

                            //bodies[i].i = invProperty.iChangRate;

                            //bodies[i].inum = (DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                        }

                        //是否批次管理
                        if (!invProperty.bInvBatch)
                        {
                            bodies[i].cBatch = "";
                        }
                        else if (string.IsNullOrEmpty(bodies[i].cBatch))
                        {
                            return string.Format("第{0}行物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                        }
                        //自由项，未处理

                        //有效期管理,根据生产日期或者失效日期推算 
                        if (invProperty.bInvQuality)
                        {
                            if (string.IsNullOrEmpty(bodies[i].dMadeDate) && string.IsNullOrEmpty(bodies[i].dDisDate))
                            {
                                return string.Format("第{0}行物料生产日期或者失效日期未录入", (i + 1).ToString());
                            }
                            else
                            {
                                bodies[i].dDisDate = DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                                bodies[i].iMassDate = DbHelper.GetDbString(invProperty.iMassDate);
                                bodies[i].cMassUnit = DbHelper.GetDbString(invProperty.cMassUnit);
                                bodies[i].dExpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                                bodies[i].iExpiratDateCalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                            }


                        }


                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
             
            return "ok";
        }


        /// <summary>
        /// 检查单据号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from AdjustPVouch where cVouchCode='{0}' ", head.cVouchCode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

         
    }
}
